<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import userService from '../services/user-service'
import Logger from '../services/logger-service'
import { CreateElement } from 'vue/types/vue'

const logger = new Logger('mod-sensitive')

@Component({ name: 'mod-sensitive' })
export default class ModContainer extends Vue {
  @Prop(Boolean)
  login: boolean

  @Prop()
  activities: string[]

  user = userService

  @Watch('user', { deep: true })
  onUserChanged (val, oval) {
    logger.debug('[Sensitive] user changed.')
    Vue.nextTick(() => {
      this.$forceUpdate()
    })
  }

  render (h: CreateElement) {
    let allow = true
    const { login, activities } = this
    if (login && !userService.isLoggin()) {
      allow = false
    }
    if (activities && !userService.hasRole(activities)) {
      allow = false
    }
    if (allow) {
      const child = this.$slots.default
      if (Array.isArray(child) && child.length > 1) {
        throw new Error('Sensitive 只接受单个子组件，需要将多个子组件用div 或 span 包裹起来.')
      }
      return child[0]
    } else {
      return h()
    }
  }
}
</script>
<style lang="less">
@import '../styles/variable.less';

.mod-container {
  background: #fff;
  padding: 0 16px;
  max-width: @container-max-width;
  margin-right: auto;
  margin-left: auto;
}
</style>
